$(function() {
    initNav();


    let userid = getCookie("userid");
    let token = getCookie("token");

    // 请求购物车数据; 
    function init() {

        var options = {
            url: "http://127.0.0.1:8888/cart/list",
            type: "GET",
            data: {
                id: userid
            },
            headers: {
                authorization: token
            },
            dataType: "json"
        };

        $.ajax(options)
            .done(function(res) {
                render(res);
            })
    }

    function render(res) {
        $(".cart-container").html(
            res.cart.map(item =>
                `<div class="goods">
                            <div class="p-goods">
                                  <div class="p-img">
                                        <img src="${item.img_small_logo}" alt="">
                                  </div>
                                  <div class="p-item">
                                        ${item.title}
                                  </div>
                            </div>
                            <div class="p-price">
                                  ￥${item.price}
                            </div>
                            <div class="p-quantity">
                                  <div class="cartnum">
                                        <button>-</button>
                                        <input type="text" value=${item.cart_number}>
                                        <button>+</button>
                                  </div>
                            </div>
                            <div class="p-sum"> ￥${ item.cart_number * item.price}</div>
                            <div class="p-options">
                                  <a id="op" data-id=${ item.goods_id} href="javascript:void(0)">删除</a>
                            </div>
                      </div>`
            ).join("")
        )

    }
    $(".cart-container").on("click", "#op", handlerAddCart)
    console.log(1)
        // 删除购物车功能 ; 
    function handlerAddCart(data) {
        var user_id = getCookie("userid");
        // 2. 获取商品 id ; 
        var goods_id = $(this).attr("data-id");
        var options = {
            url: `http://127.0.0.1:8888/cart/remove`,
            type: "GET",
            data: {
                id: user_id,
                goodsId: goods_id
            },
            headers: {
                authorization: token
            }
        }
        $.ajax(options)
            .done(function(data) {
                console.log(data);
                // handlerAddCart(data)
                init()
            });
    }
    init();
});